<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Extensions\Tenant\MainSiteMetaButton;
use App\Admin\Actions\Extensions\Tenant\PayModelCodeButton1;
use App\Admin\Actions\Extensions\Tenant\PayModelCodeButton2;
use App\Admin\Actions\Extensions\Tenant\PayModelCodeButton3;
use App\Admin\Actions\Extensions\Tenant\PayModelCodeButton4;
use App\Admin\Actions\Extensions\Tenant\TenantMetaButton;
use App\Admin\Actions\Extensions\Tenant\TenantUrlReplaceButton;
use App\Admin\Actions\Grid\Tenant\TenantShareAction;
use App\Admin\Repositories\WxTenant;
use App\Jobs\UnpreparedSqlExecute;
use App\Models\System\ChinaArea;
use App\Wen\Utils\StrUtils;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Metrics\Card;

class WxTenantController extends AdminController
{


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxTenant(), function (Grid $grid) {
            $grid->quickSearch(['tenant_id', 'name', 'short', 'desc'])->placeholder('搜索分站ID,名字,简称，描述等...')->width(30);
            $grid->model()->orderBy('order', 'desc');
            $grid->column('tenant_id')->sortable();
            $grid->column('order')->editable()->sortable();
            $grid->column('name')->editable();
            $grid->column('short')->editable();
            $grid->column('logo')->image('', 50, 50);
            $grid->column('desc')->editable();
            $grid->column('is_hot', '热门')->switch();
            $grid->column('status')->select([0=>'在运营', 1=>'关闭']);
            $grid->column('auth', '授权')->display(function (){
                global $__MINI_GLOBAL_TENANTS_ARR__;
                if(in_array($this->tenant_id, $__MINI_GLOBAL_TENANTS_ARR__)){
                    return '<span style="color: violet;">已授权</span>';
                }else{
                    return '未授权';
                }
            });
            $grid->column('tip')->display('查看')->expand(function ($v) {
                $input = $this->tip;
                if (empty($input)) {
                    return '';
                }
                $card = Card::make(view('admin/system/log', compact('input')));
                return $card;
            });
            $grid->column('bg_url', '后台')->display(function (){
                if(env('APP_IS_MULTI_SITE', 0) > 0) {
                    if (!_empty_($this->add_city) && $this->add_city > 0 && _empty_($this->city)) {
                        $city_name = ChinaArea::where('code', $this->add_city)->value('name');
                        if ($city_name) {
                            if (StrUtils::endsWith($city_name, '市')) {
                                $city_name = str_replace('市', '', $city_name);
                            }
                            if (StrUtils::endsWith($city_name, '自治区')) {
                                $city_name = str_replace('自治区', '', $city_name);
                            }
                            if (StrUtils::endsWith($city_name, '自治州')) {
                                $city_name = str_replace('自治州', '', $city_name);
                            }
                            if (StrUtils::endsWith($city_name, '盟')) {
                                $city_name = str_replace('盟', '', $city_name);
                            }
                            if (StrUtils::endsWith($city_name, '直辖市')) {
                                $city_name = str_replace('直辖市', '', $city_name);
                            }
                            if ($city_name != '市辖区') {
                                \App\Models\WxTenant::where('tenant_id', $this->tenant_id)->update(['city' => $city_name]);
                            }
                        }
                    }
                }
                if($this->tenant_id > 0){
                    return '<a href="'.(admin_base_path().'_'.$this->tenant_id).'" target="_blank">后台入口</a>';
                }
                return  '';
            });
            $grid->column('created_at')->sortable();
//            $grid->column('updated_at')

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('tenant_id');
            });

            $grid->tools([
                new MainSiteMetaButton(),
                new TenantMetaButton(),
                new TenantUrlReplaceButton(),
                new PayModelCodeButton1(),
                new PayModelCodeButton2(),
                new PayModelCodeButton3(),
                new PayModelCodeButton4()
            ]);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append((new TenantShareAction())->setKey($this->tenant_id));
            });

//            $grid->disableDeleteButton();
//            $grid->disableBatchDelete();

            $grid->header(function ($collection) {
                return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;display: inline-block;margin-top: 20px;">
活动: 鼓励更多朋友参与进mini的代理，你每成交一个代理授权，将会获得大礼包之一（礼包1：三个分站授权+50模块代金卷）（礼包2：150模块代金劵），我做这些不是为了赚多少钱，只是希望mini可以存在的时间更长一点，不要某一天突然消失在互联网，这是互利共赢的事情。</div>';
            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxTenant(), function (Show $show) {
            $show->field('tenant_id');
            $show->field('order');
            $show->field('name');
            $show->field('short');
            $show->field('logo');
            $show->field('desc');
            $show->field('status');
            $show->field('tip');
            $show->field('add_province');
            $show->field('add_city');
            $show->field('add_district');
            $show->field('add_longitude');
            $show->field('add_latitude');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxTenant(), function (Form $form) {
            $form->html(function () {
                return '<div style="background-color: #efe8d9; color: #dea550; padding: 10px;">提示: 新增分站的时候，提示保存失败，你可以返回到列表，其实已经新增成功了，这个问题后面修复，不影响啥。</div>';
            }, '');
            if($form->isCreating()){
                $form->text('tenant_id')->required()->help('不可与已有的重复');
            }else{
                $form->display('tenant_id')->help('分站一旦创建，ID不允许修改');
            }
            $form->number('order');
            $form->text('name')->required();
            $form->text('short');
            $form->image('logo')->url('files/uploads')->uniqueName()->autoUpload();
            $form->text('desc');
            $form->radio('status')->options([0=>'运营中', '关闭'])->default(0);
            $form->switch('is_hot', '热门')->options([0=>'否', 1=>'是'])->default(0);
            $form->textarea('tip');

            if(__system_is_model_enable('weiwait', 'dcat-distpicker')){
                try{
                    $form->distpicker(['add_province', 'add_city', 'add_district'], '地址')
//                ->deitail('add_detail') // 使用地址详细
                        ->coordinate(['add_longitude', 'add_latitude']) // 使用经度纬度坐标
                        ->height(800); // 设置地图高度 默认300
//                ->disableMap(); // 关闭地图
                }catch (\Exception $e){
                    UnpreparedSqlExecute::dispatch('china_areas');
                    $form->html(function () {
                        return '<div style="color: #ffffff; padding: 10px; display: inline-block; background-color: black; border-radius: 5px;">如果你看到这个提示，请等5s钟后，刷新浏览器，如果该提示还在，请联系群主</div>';
                    }, '');
                }
            }else{
                $form->html(function () {
                    return '<div style="color: #ffffff; padding: 10px; display: inline-block; background-color: black; border-radius: 5px;">!!! 请去<a href="'.admin_url('extension').'" target="_blank">扩展模块</a>，启用：《坐标拾取》模块</div>';
                }, '');
            }

            $form->display('created_at');
            $form->display('updated_at');

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
                if($form->getKey() === 0 || $form->getKey() == 999){
                    return $form->response()->error('不能删除0和999！');
                }
            });
        });
    }
}
